package com.jumi.microservice.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import com.jm.member.common.core.exception.BaseException;
import com.jm.member.common.messages.config.AliMessagesConfig;
import com.jm.member.common.messages.entity.AliResponse;
import com.jm.member.common.messages.service.AliMessageService;
import com.jm.member.common.redis.service.RedisService;

import java.util.List;
import java.util.concurrent.TimeUnit;

public class MessageUtil {



    public static AliResponse sendSms(AliMessageService messageService, RedisService redisService, String type,String mobile){
        AliMessagesConfig messagesConfig = messageService.getMessagesConfig();
        List prefixList = messagesConfig.getPrefixList();
        if(!prefixList.contains(type)){
            throw new BaseException(500,"没有此类型的短信验证!");
        }
        checkMobile(mobile);//检查手机号
        String loginKey = type+mobile;//拼接redisKey
        AliResponse reponse;
        // 每次调用请求 重置 redis里的缓存值
        reponse = messageService.sendSms(mobile, "聚米团", "SMS_186945553");
        // 设置验证码失效时间 120秒
        Integer timeout=messageService.getTime();
        redisService.setCacheObject(loginKey,reponse.getMessageCode(),timeout, TimeUnit.SECONDS);
        // 返回值里清除验证码
        reponse.setMessageCode("");
        return reponse;
    }


    public  static void checkMobile(String mobile){
        boolean match = ReUtil.isMatch( "^1[0-9]{10}$", mobile);
        if(!match){
            throw new BaseException(500,"请输入正确的手机号!");
        }
    }

    public static void checkCode(String code,RedisService redisService,String key){
        Object cacheObject = redisService.getCacheObject(key);
        /**测试 注释**/
//        if(ObjectUtil.isEmpty(cacheObject)||!code.equals(cacheObject.toString())){
//            throw new BaseException(500,"验证码不正确!");
//        }else{
//            // 验证成功后,清空redis
//            redisService.deleteObject(key);
//        }
    }

}
